<template>
  <BaseMainSlot
    :show-tab="true"
  >
    <template v-slot:search-box>
      <SearchForm :formConfig="formConfig" :formData="searchlist" @search="search"></SearchForm>
    </template>
    <template v-slot:btn-box>
      <ActionBar
        :page-no="76"
        :add-active="addActive"
        :del-active="delActive"
        :has-edit="false"
        :has-save="false"
        :has-cancel="false"
        :has-del="false"
        @add="add"
        @del="del"
      />
    </template>
    <template v-slot:table-box>
      <Table @sortChange="changeTableSort" :propList="tableColumn" v-loading="loading"
        :listData="tableData" @handleSelectionChange="handleSelectionChange">
        <template v-slot:operation="{ row }">
          <template v-if="!row.index">
            <!-- <el-button
              v-if="judgePermission(76, 'edit') && forderStatus === 0"
              class="text-btn-cursor"
              type="text"
              size="small"
              @click="edit(row)"
            >
              <i class="el-icon-edit-outline"></i> 修改
            </el-button>-->
            <el-button
              v-if="judgePermission(76, 'edit') && forderStatus === 0"
              class="text-btn-cursor"
              type="text"
              size="small"
              @click="goTo(row)"
            >
              <i class="el-icon-edit-outline"></i> 出库
            </el-button>
            <!-- <el-button
              v-if="judgePermission(76, 'delete') && forderStatus === 0"
              class="text-btn-cursor cursor-delete"
              type="text"
              size="small"
              @click="handleDelete(row.deliveryNo)"
            >
              <i class="el-icon-delete"></i> 删除
            </el-button> -->
          </template>
        </template>
        <template v-slot:viewList="{ row }">
          <template v-if="!row.index">
            <el-button
              class="text-btn-cursor"
              type="text"
              size="small"
              @click="lookInfo(row.deliveryNo)"
            >
              <i class="el-icon-view"></i>查看发货明细
            </el-button>
          </template>
        </template>
      </Table>
      <Pagination
        :page-size="pageSize"
        :current-page="currentPage"
        :total-size="totalSize"
        @changePageSize="changePageSize"
        @changeCurrentPage="changeCurrentPage"
      />
    </template>
    <template v-slot:dialog>
      <el-dialog
        :title="titleText"
        :visible.sync="dialogFormVisible"
        @close="cancel('formData')"
      >
        <el-form
          ref="formData"
          label-position="left"
          :model="formData"
          :rules="rules"
          class="el-form"
        >
          <!-- 添加 -->
          <template v-for="item,index in formDatalists">
            <el-form-item
              v-if="item.edit !== 'edit' && nowChanceStau === 'add'"
              :key="index"
              :label="item.name + ':'"
              :prop="item.type === 'Select'? item.selectValue : item.prop"
              class="w50p"
              :rules="[
                { required: item.required, message: item.name + '不能为空', trigger: ['blur' ,'change']}
              ]"
            >
              <el-input
                v-if="item.type === 'input'"
                v-model="formData[`${item.prop}`]"
                :placeholder="'请输入' + item.name"
                clearable
              />
              <el-select
                v-if="item.type === 'Select'"
                v-model="formData[`${item.selectValue}`]"
                filterable
                :placeholder="'请选择' + item.name"
                clearable
                @change="getSelectData($event, item.prop)"
              >
                <el-option
                  v-for="items,indexs in item.typeObj.list"
                  :key="indexs"
                  :label="items.name"
                  :value="items.value"
                />
              </el-select>
              <el-date-picker
                v-if="item.type === 'TimePicker'"
                v-model="formData[`${item.prop}`]"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm"
                :placeholder="'选择' + item.name"
                @change="timeEvent($event,item.prop)"
              />
            </el-form-item>
          </template>
          <!-- 选择发货商品 -->
          <el-divider
            v-if="nowChanceStau === 'add'"
            content-position="left"
          >发货明细</el-divider>
          <el-form-item
            v-if="nowChanceStau === 'add'"
            label="发货商品 :"
            class="w50p"
          >
            <el-checkbox-group
              v-model="formData.deliveryGoodsList"
              @change="chooseGoods"
            >
              <el-checkbox
                v-for="items,indexs in deliveryGoodsList"
                :key="indexs"
                :label="items"
              >{{ items.materialName }}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>

          <div
            v-for="orderDetail,index in formData.deliveryDetailList"
            :key="orderDetail.key"
            class="w100p xunhuan"
          >
            <div class="w100p goods">发货商品{{ index + 1 }}</div>
            <el-form-item
              label="商品名称 :"
              :prop="'deliveryDetailList.' + index + '.materialNo'"
              class="w50p"
              :rules="[{required: true,message:'商品名称不能为空',trigger:'change'}]"
            >
              <el-select
                v-model="orderDetail.materialNo"
                placeholder="请选择商品（物料）名称"
                clearable
                disabled
                @change="getGoods($event,index)"
              >
                <el-option
                  v-for="items,indexs in materialList"
                  :key="indexs"
                  :label="items.materialName"
                  :value="items.materialNo"
                />
              </el-select>
            </el-form-item>

            <el-form-item
              label="发货仓库 :"
              :prop="'deliveryDetailList.' + index + '.stordocNo'"
              class="w50p"
            >
              <el-select
                v-model="orderDetail.stordocNo"
                placeholder="请选择收货仓库"
                clearable
                disabled
              >
                <el-option
                  v-for="items,indexs in stordocList"
                  :key="indexs"
                  :label="items.stordocName"
                  :value="items.stordocNo"
                />
              </el-select>
            </el-form-item>
            <!-- <el-form-item
              label="批号 :"
              :prop="'deliveryDetailList.' + index + '.lotNumber'"
              class="w50p"
            >
              <el-input
                v-model="orderDetail.lotNumber"
                clearable
                placeholder="请输入批号"
              />
            </el-form-item>-->
            <el-form-item
              label="单位 :"
              :prop="'deliveryDetailList.' + index + '.castUnitNo'"
              class="w50p"
              :rules="[{required: true,message:'单位不能为空',trigger:'change'}]"
            >
              <el-select
                v-model="orderDetail.castUnitNo"
                placeholder="请选择单位"
                disabled
                clearable
              >
                <el-option
                  v-for="items,indexs in unitList"
                  :key="indexs"
                  :label="items.symbol||items.unitName"
                  :value="items.unitNo"
                />
              </el-select>
            </el-form-item>
            <el-form-item
              label="应发货数量 :"
              :prop="'deliveryDetailList.' + index + '.shouldSendNum'"
              class="w50p numberUnit"
              :rules="[{pattern: /^([1-9]\d*(\.\d*[1-9][0-9])?)|(0\.\d*[1-9][0-9])|(0\.\d*[1-9])$/,message:'值该为大于0的数',trigger: ['change','blur']},
                       {required: true,message:'数量不能为空',trigger:'change'}]"
            >
              <el-input
                v-model="orderDetail.shouldSendNum"
                clearable
                class="one"
                disabled
                placeholder="请输入应发货数量"
              />
              <el-select
                v-model="orderDetail.castUnitNo"
                placeholder="请选择单位"
                disabled
                class="two"
                clearable
              >
                <el-option
                  v-for="items,indexs in unitList"
                  :key="indexs"
                  :label="items.symbol||items.unitName"
                  :value="items.unitNo"
                />
              </el-select>
            </el-form-item>
            <el-form-item
              label="实发货数量 :"
              :prop="'deliveryDetailList.' + index + '.confirmQuantity'"
              class="w50p numberUnit"
              :rules="[{pattern: /^([1-9]\d*(\.\d*[1-9][0-9])?)|(0\.\d*[1-9][0-9])|(0\.\d*[1-9])$/,message:'值该为大于0的数',trigger: ['change','blur']},
                       {required: true,message:'数量不能为空',trigger:'change'}]"
            >
              <el-input
                v-model="orderDetail.confirmQuantity"
                class="one"
                clearable
                placeholder="请输入实发货数量"
              />
              <el-select
                v-model="orderDetail.castUnitNo"
                placeholder="请选择单位"
                disabled
                class="two"
                clearable
              >
                <el-option
                  v-for="items,indexs in unitList"
                  :key="indexs"
                  :label="items.symbol||items.unitName"
                  :value="items.unitNo"
                />
              </el-select>
            </el-form-item>
            <el-form-item
              label="换算率 :"
              :prop="'deliveryDetailList.' + index + '.exchangeRate'"
              class="w50p"
              :rules="[{pattern: /^([1-9]\d*(\.\d*[1-9][0-9])?)|(0\.\d*[1-9][0-9])|(0\.\d*[1-9])$/,message:'值该为大于0的数',trigger: ['change','blur']},
                       {required: true,message:'换算率不能为空',trigger:'change'}]"
            >
              <el-input
                v-model="orderDetail.exchangeRate"
                clearable
                placeholder="请输入换算率"
                disabled
              />
            </el-form-item>
            <div class="zhu w50p">
              <el-form-item
                label="主数量&主单位 :"
                :prop="'deliveryDetailList.' + index + '.primaryQuantity'"
                style="width: 82%;"
                :rules="[{required: true,message:'数量不能为空',trigger:'change'},{pattern: /^\d+$/,message:'值该为正整数',trigger: ['change','blur']},
                ]"
              >
                <el-input
                  v-model="orderDetail.primaryQuantity"
                  clearable
                  disabled
                  placeholder="请输入主数量"
                />
              </el-form-item>
              <el-form-item
                :prop="'deliveryDetailList.' + index + '.unitNo'"
                style="width: 18%;"
                :rules="[{required: true,message:'主单位不能为空',trigger:'change'}]"
              >
                <el-select
                  v-model="orderDetail.unitNo"
                  placeholder="请选择单位"
                  disabled
                  clearable
                >
                  <el-option
                    v-for="items,indexs in unitList"
                    :key="indexs"
                    :label="items.symbol||items.unitName"
                    :value="items.unitNo"
                  />
                </el-select>
              </el-form-item>
            </div>
            <el-form-item
              label="单价 :"
              :prop="'deliveryDetailList.' + index + '.price'"
              class="w50p"
              :rules="[{required: true,message:'单价不能为空',trigger:'change'}]"
            >
              <el-input
                v-model="orderDetail.price"
                clearable
                disabled
                placeholder="请输入单价"
              />
            </el-form-item>
            <el-form-item
              label="折扣 :"
              :prop="'deliveryDetailList.' + index + '.discount'"
              class="w50p"
            >
              <el-input
                v-model="orderDetail.discount"
                clearable
                disabled
                placeholder="请输入折扣"
              />
            </el-form-item>
            <el-form-item
              label="折扣额 :"
              :prop="'deliveryDetailList.' + index + '.discountPrice'"
              class="w50p"
            >
              <el-input
                v-model="orderDetail.discountPrice"
                clearable
                disabled
                placeholder="请输入折扣额"
              />
            </el-form-item>
            <el-form-item
              label="价税合计 :"
              :prop="'deliveryDetailList.' + index + '.totalPrice'"
              class="w50p"
              :rules="[{required: true,message:'价税合计不能为空',trigger:'change'}]"
            >
              <el-input
                v-model="orderDetail.totalPrice"
                clearable
                disabled
                placeholder="请输入价税合计"
              />
            </el-form-item>
            <!-- <el-form-item
              label="重量 :"
              class="w50p"
              :rules="[{required: false , type:'number',trigger:'change'}]"
            >
              <el-input
                v-model="orderDetail.weight"
                clearable
                disabled
                placeholder="请输入重量"
              />
            </el-form-item>-->
            <!-- <el-form-item
              label="体积 :"
              class="w50p"
              :rules="[{required: false ,type:'number',trigger:'change'}]"
            >
              <el-input
                v-model="orderDetail.volume"
                clearable
                disabled
                placeholder="请输入体积"
              />
            </el-form-item>-->
            <el-form-item
              label="发货日期 :"
              :prop="'deliveryDetailList.' + index + '.sendTime'"
              class="w50p"
              :rules="[{required: true,message:'发货不能为空',trigger:'change'}]"
            >
              <el-date-picker
                v-model="orderDetail.sendTime"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm"
                clearable
                placeholder="请选择发货日期"
              />
            </el-form-item>
            <el-form-item
              label="发货地址 :"
              :prop="'deliveryDetailList.' + index + '.deliverAdd'"
              class="w50p"
              :rules="[{required: true,message:'发货地址不能为空',trigger:'change'}]"
            >
              <el-select
                v-model="orderDetail.deliverAdd"
                placeholder="请选择发货地址"
                clearable
              >
                <el-option
                  v-for="items,indexs in addressList"
                  :key="indexs"
                  :label="items.spliceAddress"
                  :value="items.spliceAddress"
                />
              </el-select>
            </el-form-item>
            <el-form-item
              label="收货地址 :"
              :prop="'deliveryDetailList.' + index + '.creceiveaddr'"
              class="w50p"
              :rules="[{required: true,message:'收货地址不能为空',trigger:'change'}]"
            >
              <el-input
                v-model="orderDetail.creceiveaddr"
                clearable
                placeholder="请输入收货地址"
              />
            </el-form-item>
            <el-form-item
              label="要求收货日期 :"
              :prop="'deliveryDetailList.' + index + '.arrivalTime'"
              class="w50p"
              :rules="[{required: true,message:'要求收货日期不能为空',trigger:'change'}]"
            >
              <el-date-picker
                v-model="orderDetail.arrivalTime"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm"
                clearable
                placeholder="请选择收货日期"
              />
            </el-form-item>
            <!-- <el-form-item
              label="收货人 :"
              :prop="'deliveryDetailList.' + index + '.receiverName'"
              class="w50p"
              :rules="[{required: true,message:'收货人不能为空',trigger:'change'}]"
            >
              <el-input
                v-model="orderDetail.receiverName"
                clearable
                placeholder="请输入收货人"
              />
            </el-form-item>
            <el-form-item
              label="收货人联系方式 :"
              :prop="'deliveryDetailList.' + index + '.receiverPhone'"
              class="w50p"
              :rules="[{required: true,message:'收货人联系方式不能为空',trigger:'change'}]"
            >
              <el-input
                v-model="orderDetail.receiverPhone"
                clearable
                placeholder="请输入收货人联系方式"
              />
            </el-form-item>-->
          </div>
        </el-form>
        <div
          v-if="nowChanceStau !== ''"
          slot="footer"
          class="dialog-footer"
        >
          <el-button
            class="zh-button-one"
            @click="cancel('formData')"
          >取 消</el-button>
          <el-button
            v-if="nowChanceStau === 'add'"
            class="zh-button-two"
            type="primary"
            @click="save('formData')"
          >保 存</el-button>
        </div>
      </el-dialog>
    </template>
  </BaseMainSlot>
</template>

<script>
import SearchForm from '@/components/searchForm';
import Table from '@/components/table/table.vue';
import ActionBar from "@/components/ActionBar";
import Pagination from "@/components/Pagination";
import BaseMainSlot from "@/components/BaseMainSlot/newBaseMainSlot";
import { mymixin } from "@/utils/mixins";
import customerApi from "@/api/livestock-manage/sale-manage/customerManage"; // 客户
import unitApi from "@/api/basic-info-manage/unit-manage"; // 单位
import materialApi from "@/api/basic-info-manage/agr-source-base-Manage"; // 物料
import saleOrderApi from "@/api/livestock-manage/sale-manage/sale-order"; // 销售订单
import saleOrderDetailApi from "@/api/livestock-manage/sale-manage/sale-order-detail"; // 销售订单明细
import warehouseApi from "@/api/livestock-manage/storage-manage/warehouse-manage"; // 仓库
import personApi from "@/api/livestock-manage/personnel-cost-mansge/staff-manage"; // 人员
import deliveryNoticeApi from "@/api/livestock-manage/sale-manage/delivery";
import deliveryDetailApi from "@/api/livestock-manage/sale-manage/delivery-detail";
import addressApi from "@/api/livestock-manage/inventory/address/addressManage";
import { mapGetters } from "vuex";

export default {
  name: "SheepInformation",
  components: { SearchForm, Table, ActionBar, Pagination, BaseMainSlot },
  mixins: [mymixin],
  data() {
    return {
      searchlist: {},
      tableColumn: [],
      formConfig: [
        {
          label: '销售订单号',
          prop: 'saleOrderNo',
          type: 'select',
          options: [],
          optionKey: { label: 'name', value: 'value' },
        },
        {
          label: '客户名称',
          prop: 'customerNo',
          type: 'select',
          options: [],
          optionKey: { label: 'name', value: 'value' },
        },
        {
          label: '发货员',
          prop: 'deliverName',
          type: 'input',
        },
        {
          label: '收货人',
          prop: 'receiverName',
          type: 'input',
        },
        {
          label: '发货日期',
          prop: 'sendTime',
          type: 'date',
        },
      ],
      addressList: [],
      forderStatus: 0,
      deliveryGoodsList: [],
      selectedStaffList: [],
      stordocList: [],
      unitList: [],
      materialList: [],
      personList: [],
      formData: {
        deliveryDetailList: []
      },
      // selectValue 用于传递select的编号
      formDatalists: [
        {
          type: "Select",
          prop: "saleOrderNo",
          selectValue: "saleOrderNo", // input Select Checkbox TimePicker
          typeObj: {},
          name: "销售订单号",
          required: true
        },
        // {
        //   type: "TimePicker", // input Select Checkbox TimePicker
        //   prop: "approvalTime",
        //   typeObj: {},
        //   name: "审批日期",
        //   required: true
        // },
        // {
        //   type: "input", // input Select Checkbox TimePicker
        //   prop: "approverName",
        //   typeObj: {},
        //   name: "审批人",
        //   required: true
        // },
        {
          type: "Select", // input Select Checkbox TimePicker
          prop: "customerName",
          selectValue: "customerNo",
          typeObj: {},
          name: "客户",
          required: true
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "totalNumber",
          typeObj: {},
          name: "总件数",
          required: true
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "totalQuantity",
          typeObj: {},
          name: "总数量",
          required: true
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "totalPrice",
          typeObj: {},
          name: "价税合计/元",
          required: true
        },
        // {
        //   type: "input", // input Select Checkbox TimePicker
        //   prop: "totalWeight",
        //   typeObj: {},
        //   name: "总重量",
        //   required: false
        // },
        // {
        //   type: "input", // input Select Checkbox TimePicker
        //   prop: "totalVolume",
        //   typeObj: {},
        //   name: "总体积",
        //   required: false
        // },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "",
          typeObj: {},
          name: "发货明细",
          edit: "edit",
          required: true,
          notSearch: true
        },
        // {
        //   type: "Select", // input Select Checkbox TimePicker
        //   prop: "deliverName",
        //   selectValue: "personNo",
        //   typeObj: {},
        //   name: "收货人",
        //   required: true
        // },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "deliverName",
          typeObj: {},
          name: "发货人",
          required: true
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "deliverPhone",
          typeObj: {},
          name: "发货人联系方式",
          required: false
        },
        {
          type: "TimePicker", // input Select Checkbox TimePicker
          prop: "sendTime",
          typeObj: {},
          name: "发货日期",
          required: true
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "receiverName",
          typeObj: {},
          name: "收货人",
          required: true
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "receiverPhone",
          typeObj: {},
          name: "收货人联系方式",
          required: true
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "remarks",
          typeObj: {},
          name: "备注",
          notSearch: true
        }
      ],
      rules: {}
    };
  },
  computed: {
    ...mapGetters({
      judgePermission: "permission/judgePermission"
    })
  },
  watch: {
    formData: {
      deep: true,
      handler(val) {
        if (val.deliveryDetailList) {
          //
        }
        sum(1);
        function sum(arr) {
          let s = 0;
          for (let i = arr.length - 1; i >= 0; i--) {
            s += parseInt(arr[i]);
          }
          return s;
        }
      }
    }
  },
  created() {
    let list = []
    this.formDatalists.map(el => {
      let obj = {
        prop: el.prop, label: el.name, minWidth: '140px'
      }
      el.name == '发货明细' && (obj.slotName = 'viewList')
      list.push(obj)
    })
    list.push({ prop: 'operation', label: '操作', slotName: 'operation', width: '150' })
    this.tableColumn = list

    this.search();
    this.getMaterialList();
    this.getCustomerList();
    this.getstordocList();
    this.getUnitList();
    this.getOederList();
    this.getPersonList();
    this.getAddressList();
  },
  methods: {
    // 获取地址
    getAddressList() {
      addressApi.conditionQuery({}).then(res => {
        if (res.code === 1) {
          this.addressList = res.data;
        }
      });
    },
    // 跳转入库
    goTo(row) {
      this.$router.push({
        name: "OutStorage",
        params: { deliveryNo: row.deliveryNo, isTo: "toAdd" }
      });
    },
    // 获取所有物料
    getMaterialList() {
      materialApi.getqueryList({}).then(res => {
        if (res.code === 1) {
          this.materialList = res.data;
        }
      });
    },
    // 获取人员列表
    getPersonList() {
      personApi.getStaffListByCondition().then(res => {
        if (res.code === 1) {
          this.personList = res.data;
          let list = [];
          res.data.forEach(item => {
            list.push({
              name: item.person.name,
              value: item.personNo
            });
          });
          // this.formDatalists.forEach((item, index) => {
          //   if (item.prop === "receiverName") {
          //     this.$set(this.formDatalists[index].typeObj, "list", list);
          //   }
          // });
        }
      });
    },
    // 获取销售所有订单
    getOederList() {
      saleOrderApi
        .conditionQuery({ completeStatus: false, forderStatus: 1 })
        .then(res => {
          if (res.code === 1) {
            let list = [];
            res.data.forEach(item => {
              list.push({
                name: item.saleOrderNo,
                value: item.saleOrderNo
              });
            });
            this.setOptions(this.formConfig, 'saleOrderNo', list)
            this.formDatalists.forEach((item, index) => {
              if (item.prop === "saleOrderNo") {
                this.$set(this.formDatalists[index].typeObj, "list", list);
              }
            });
          }
        });
    },
    getCount(event, index) {
      let a = this.formData.deliveryDetailList[index].produceDate; // 生产日期
      let b = this.formData.deliveryDetailList[index].lifeDays; // 保质期
      let c = this.formData.deliveryDetailList[index].expirationDate; // 失效日期
      if (a && b) {
        let time = new Date(a.replace(/-/, "/"));
        let newDate = new Date(time.getTime() + b * (1000 * 60 * 60 * 24));
        console.log(newDate);
        let year = newDate.getFullYear();
        let mon = newDate.getMonth() + 1;
        let day = newDate.getDate();
        console.log(year, mon, day);
        let date = year + "-" + mon + "-" + day;
        this.$set(
          this.formData.deliveryDetailList[index],
          "expirationDate",
          date
        );
      }
      if (a && c) {
        let a1 = Date.parse(new Date(a));
        let a2 = Date.parse(new Date(c));
        let day = parseInt((a2 - a1) / (1000 * 60 * 60 * 24));
        this.$set(this.formData.deliveryDetailList[index], "lifeDays", day);
      }
    },
    // 获取仓库X
    getstordocList() {
      warehouseApi.conditionQuery({}).then(res => {
        if (res.code === 1) {
          this.stordocList = res.data;
        }
      });
    },
    // 获取单位列表X
    getUnitList() {
      unitApi.getPlantingUnitListByCondition({}).then(res => {
        if (res.code === 1) this.unitList = res.data;
      });
    },
    // 获取客户
    getCustomerList() {
      customerApi.conditionQuery({}).then(res => {
        if (res.code === 1) {
          let list = [];
          // 提供表头搜索数据
          res.data.forEach(item => {
            list.push({
              name: item.customerName,
              value: item.customerNo
            });
          });
          this.setOptions(this.formConfig, 'customerNo', list)
          this.formDatalists.forEach((item, index) => {
            if (item.prop === "customerName") {
              this.$set(this.formDatalists[index].typeObj, "list", list);
            }
          });
        }
      });
    },
    timeEvent(event, prop) {
      if (prop === "sendTime") {
        this.formData.deliveryDetailList.forEach((item, index) => {
          this.$set(this.formData.deliveryDetailList[index], "sendTime", event);
        });
      }
    },
    // 获取单个商品
    getGoods(event, index) {
      materialApi.getqueryList({ materialNo: event }).then(res => {
        this.formData.deliveryDetailList[index].unitNo = res.data[0].unitNo;
        this.formData.deliveryDetailList[index].castUnitNo = res.data[0].unitNo;
      });
    },
    // 获取单个供应商
    getSelectData(event, prop) {
      // 获取单个销售订单
      if (prop === "saleOrderNo" && event) {
        saleOrderApi.numberQuery(event).then(res => {
          if (res.code === 1) {
            this.formData = { ...res.data };
            // this.formData.totalVolume = Number(res.data.totalVolume);
            // this.formData.totalWeight = Number(res.data.totalWeight);
            this.getOrderDetailList(event);
          }
        });
      } else {
        return;
      }
    },
    // 获取订单详细列表
    getOrderDetailList(e) {
      saleOrderDetailApi.queryListBySaleOrderNo(e).then(res => {
        if (res.code === 1) {
          this.$set(this.formData, "deliveryGoodsList", []);
          this.deliveryGoodsList = res.data;
          this.$set(this.formData, "deliveryGoodsList", [
            this.deliveryGoodsList[0]
          ]);
          this.chooseGoods([this.deliveryGoodsList[0]]);
        }
      });
    },
    // 选择发货商品
    chooseGoods(e) {
      let price = 0;
      this.$set(this.formData, "deliveryDetailList", e);
      this.formData.deliveryDetailList.forEach((item, index) => {
        this.formData.deliveryDetailList[index].organizationNo =
          sessionStorage.organizationNo;
        this.$set(
          this.formData.deliveryDetailList[index],
          "shouldSendNum",
          item.confirmQuantity
        );
        this.$set(
          this.formData.deliveryDetailList[index],
          "arriveTime",
          this.formData.arriveTime
        );
        price += item.totalPrice;
      });
      this.$set(this.formData, "totalPrice", price);
    },
    getTableDataList() {
      this.loading = true;
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        organizationNo: sessionStorage.organizationNo,
        breedTypeNo: sessionStorage.breedTypeNo,
        entity: {
          ...this.searchlist,
          sendTime: this.searchlist.sendTime && this.searchlist.sendTime+' 00:00:00'
        }
      };
      deliveryNoticeApi.pageQuery(params).then(res => {
        this.loading = false;
        let data = res.data;
        if (data) {
          this.totalSize = data.totalElements;
          this.tableData = data.content;
          this.addblankmet();
          this.resetActionBar();
        }
      });
    },
    handleSelectionChange(list) {
      this.selectedStaffList = [];
      this.selectedStaffList = list.map(item => item.saleOrderNo);
      if (this.selectedStaffList.length > 0) this.delActive = true;
      else this.delActive = false;
    },
    delmessage() {
      deliveryNoticeApi
        .numberBatchDel({ noList: this.selectedStaffList })
        .then(res => {
          if (res.code === 1) {
            this.$message.success(res.msg);
            this.search();
          } else {
            this.$message.warning(res.msg || "删除失败");
          }
        });
    },
    handleDelete(val) {
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass"
      })
        .then(() => {
          deliveryNoticeApi.numberDel(val).then(res => {
            if (res.code === 1) {
              this.$message.success(res.msg);
              this.search();
            } else {
              this.$message.warning(res.msg || "删除失败");
            }
          });
        })
        .catch(() => {});
    },
    add() {
      this.formData = {};
      this.deliveryGoodsList = [];
      this.nowChanceStau = "add";
      this.titleText = "添加发货通知";
      this.addActive = false;
      this.delActive = false;
      this.dialogFormVisible = true;
    },
    edit(row) {
      this.formData = { ...row };
      saleOrderDetailApi.numberQuery(row.saleOrderNo).then(res => {
        this.$set(this.formData, "deliveryDetailList", res.data);
      });
      this.nowChanceStau = "edit";
      this.titleText = "修改发货通知";
      this.dialogFormVisible = true;
      this.addActive = true;
      this.delActive = false;
    },
    lookInfo(e) {
      this.formData = {};
      deliveryDetailApi.queryListByDeliveryNo(e).then(res => {
        if (res.code === 1) {
          this.$set(this.formData, "deliveryDetailList", res.data);
        }
      });
      this.nowChanceStau = "lookInfo";
      this.titleText = "查看发货明细";
      this.dialogFormVisible = true;
      this.addActive = true;
      this.delActive = false;
    },
    addDetail(e, index) {
      let validateFieldList = [];
      this.$refs["formData"].validateField(
        [
          "deliveryDetailList." + index + ".materialNo",
          "deliveryDetailList." + index + ".confirmQuantity",
          "deliveryDetailList." + index + ".castUnitNo",
          "deliveryDetailList." + index + ".unitNo",
          "deliveryDetailList." + index + ".exchangeRate",
          "deliveryDetailList." + index + ".primaryQuantity",
          "deliveryDetailList." + index + ".price",
          "deliveryDetailList." + index + ".packNum",
          "deliveryDetailList." + index + ".totalPrice",
          "deliveryDetailList." + index + ".address"
        ],
        valid => {
          if (!valid) {
            validateFieldList.push(valid);

            // 因为我这里总共校验了三个字段,所有最终三个字段都校验成功之后,数组中会有三个""
            if (
              validateFieldList.length === 10 &&
              validateFieldList.every(item => item === "")
            ) {
              saleOrderDetailApi.add(e).then(res => {
                if (res.code === 1) {
                  this.$message.success(res.msg);
                  saleOrderDetailApi.numberQuery(e.saleOrderNo).then(res => {
                    this.$set(this.formData, "orderDetailList", res.data);
                  });
                } else {
                  this.$message.warning(res.msg || "添加失败");
                }
              });
            }
            // 校验不通过走这里
            return;
          } else {
            return false;
          }
        }
      );
    },
    editDetail(e) {
      this.$confirm("确定修改该条数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass"
      })
        .then(() => {
          saleOrderDetailApi.edit(e).then(res => {
            if (res.code === 1) {
              this.$message.success(res.msg);
            } else {
              this.$message.warning(res.msg || "修改失败");
            }
          });
        })
        .catch(() => {});
    },
    delDetial(e, index) {
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass"
      })
        .then(() => {
          saleOrderDetailApi.numberQuery(e.saleOrderNo).then(res => {
            if (res.data.length <= 1) {
              this.$message.warning("已是最后一条数据禁止删除");
            } else {
              saleOrderDetailApi.numberDel(e.orderDetailNo).then(res => {
                if (res.code === 1) {
                  this.$message.success(res.msg);
                  this.formData.orderDetailList.splice(index, 1);
                } else {
                  this.$message.warning(res.msg || "删除失败");
                }
              });
            }
          });
        })
        .catch(() => {});
    },
    save(formData) {
      this.$refs[formData].validate(valid => {
        if (valid) {
          // 添加仓库名称
          this.formData.deliveryDetailList.forEach((item, index) => {
            if (item.stordocNo) {
              this.stordocList.forEach(item1 => {
                if (item1.stordocNo === item.stordocNo) {
                  this.formData.deliveryDetailList[index].stordocName =
                    item1.stordocName;
                }
              });
            }
          });
          if (this.nowChanceStau === "edit") {
            deliveryNoticeApi.edit(this.formData).then(res => {
              if (res.code === 1) {
                this.$message.success(res.msg || "修改成功！");
                this.dialogFormVisible = false;
                this.search();
                this.$refs[formData].resetFields();
              } else {
                this.$message.error(res.msg || "修改失败！");
              }
            });
          } else if (this.nowChanceStau === "add") {
            deliveryNoticeApi.add(this.formData).then(res => {
              if (res.code === 1) {
                this.$message.success(res.msg || "新增成功！");
                this.dialogFormVisible = false;
                this.search();
                this.$refs[formData].resetFields();
              } else {
                this.$message.error(res.msg || "新增失败！");
              }
            });
          }
        } else {
          return false;
        }
      });
    }
  }
};
</script>
<style scoped lang="scss">
@import "~@/styles/variables.scss";
::v-deep
  .el-dialog__wrapper
  .el-dialog
  .el-dialog__body
  .el-form
  .el-form-item
  .el-form-item__label {
  min-width: 140px;
}
.xunhuan {
  margin-top: 20px;
  position: relative;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  .goods {
    font-size: 20px;
    font-weight: bold;
    margin-bottom: 20px;
    text-align: left;
    padding-left: 140px;
  }
  .editBox {
    position: absolute;
    right: 0px;
    bottom: -30px;
  }
}
.addone {
  margin-left: 140px;
}
.zhu {
  display: flex;
  ::v-deep .el-input__inner {
    background-color: rgb(241, 239, 239) !important;
  }
}
.numberUnit {
  display: flex;
  .one {
    width: 75%;
  }
  .two {
    width: 25%;
  }
}
</style>
